<?php
/**
 * Created by PhpStorm.
 * User: chuyun
 * Date: 2018/8/14
 * Time: 10:13
 */

namespace App\Controllers;


use App\Models\Access;
use App\Models\Node;
use Interop\Container\ContainerInterface;
use Slim\Http\Request;
use Respect\Validation\Validator as v;

class NodeController extends BaseController
{
    public function __construct(ContainerInterface $container)
    {
        parent::__construct($container);
    }

    public function nodeList(Request $request) {
        $list   = $this->getNodeLoop(0);
        return $this->jsonWithData(1,'OK',$list);
    }

    public function nodeStore(Request $request){
        $params = $request->getParsedBody();
        //校验
        if(isset($params['id']) && $params['id']>0) {
            $validate =  $this->container->validator->validateArray($params,
                [
                    'title' => v::noWhitespace()->notEmpty()->setTemplate('请输入权限中文名'),
                ]);
            if($validate->failed()){
                $errors = $validate->getErrors();
                foreach ($errors as $item){
                    $message = $item[0];
                    break;
                }
                return $this->json(1005,$message);
            }
            $node         = Node::where('id',$params['id'])->first();
            $node->title  = $params['title'];
            $node->url    = $params['url'];
            $node->sort   = $params['sort'];
            $node->level  = $params['level'];
            if($node->save()){
                return $this->json(1,'OK');
            }else{
                return $this->json(1,'修改失败');
            }
        } else {
            $validate =  $this->container->validator->validateArray($params,
                [
                    'name'    => v::noWhitespace()->notEmpty()->existsInTable($this->container->db->table('node'), 'name')->setTemplate('同名的权限节点已存在或权限节点为空'),
                    'title' => v::noWhitespace()->notEmpty()->setTemplate('请输入权限节点中文名称')
                ]);
            if($validate->failed()){
                $errors = $validate->getErrors();
                foreach ($errors as $item){
                    $message = $item[0];
                    break;
                }
                return $this->json(1005,$message);
            }
            $node = new Node();
            $node->name   = $params['name'];
            $node->title  = $params['title'];
            $node->url    = $params['url'];
            $node->sort   = isset($params['sort'])&&!empty($params['sort'])?$params['sort']:0;
            $node->level  = $params['level'];
            $node->pid    = isset($params['pid'])&&!empty($params['pid'])?$params['pid']:0;
            if($node->save()){
                return $this->json(1,'OK');
            }else{
                return $this->json(1,'创建失败');
            }
        }
    }

    public function nodeDelete(Request $request) {
        $params = $request->getParsedBody();
        if(intval($params['id'])==0){
            return $this->json(1005,'id不合法');
        }
        $nodeCount = Node::where('pid',$params['id'])->count();
        if($nodeCount){
            return $this->json(0,'该权限存在子权限，不允许删除！');
        }

        $accessCount = Access::where('node_id',$params['id'])->count();
        if($accessCount){
            return $this->json(0,'该权限已使用，不允许删除！');
        }
        $ret = Node::where('id',$params['id'])->delete();
        if($ret){
            return $this->json(1,'OK');
        } else {
            return $this->json(0,'删除失败');
        }
    }

    public function getNodeLoop($id) {
        $nodeList = Node::where(['pid'=>$id])->get();
        $list     = [];
        $i        = 0;
        foreach ($nodeList as $key => $val){
            $list[$i]['id']         = $val->id;
            $list[$i]['name']       = $val->name;
            $list[$i]['pid']        = $val->pid;
            $list[$i]['title']      = $val->title;
            $list[$i]['url']        = $val->url;
            $list[$i]['sort']       = $val->sort;
            $list[$i]['level']      = $val->level;
            $list[$i]['level_str']  = $val->level==1?"导航菜单":'按钮';
            $list[$i]['status']     = $val->name;
            $children = $this->getNodeLoop($val->id);
            if($children){
                $list[$i]['children'] = $children;
            }
            $i++;
        }
        return $list;
    }
}